﻿using UnityEngine;
using System.Collections.Generic;
using SGLib.Net;
using SGLib.Scene;
using SGLisp;

public class Game : MonoBehaviour
{
    GameNet mGameNet;
    static Game mGame;
    public static Game Inst { get { return mGame; } }
    public GameNet Net { get { return mGameNet; } }

    public Table mTable = new Table();
    public Table Table { get { return mTable; } }

    public GameContext mContext;
    public GameContext Context { get { return mContext; } }

    public static string TABLE_PATH;
    void Awake()
    {
        TABLE_PATH = Application.dataPath + "../../../../Common/Table/";
        mGame = this;
    }
    void Start()
    {
        SGLisp.RT.InitRuntime();
        mContext = new GameContext();
        mTable.Load(TABLE_PATH);
        DontDestroyOnLoad(gameObject);
        mGameNet = gameObject.GetComponent<GameNet>();
        SceneManager.Instance.LoadScene<LobbyScene>();
    }

    void Update()
    {
        if (SceneManager.Instance.CurScene != null)
        {
            SceneManager.Instance.CurScene.OnUpdate();
        }
    }
}

public class GameContext : Context
{
    public GameContext()
    {
        this.Parent = SGLisp.RT.MainContext;
        this.Define("log", new FunctionNode(_log));
        this.Define("set-animator", new FunctionNode(_set_animator));
        this.Define("set-active", new FunctionNode(_set_active));
    }
    static ASTNode _log(List<ASTNode> args, Context context)
    {
        args = CoreFunction.EvalArgs(args,context);
        Debug.Log(args[0].ToString());
        return null;
    }

    static ASTNode _set_animator(List<ASTNode> args, Context context)
    {
        args = CoreFunction.EvalArgs(args, context);
        Actor  curActor = (Actor)((ObjectNode)args[0]).Val;
        string animName = (string)((StringNode)args[1]).Val;
        curActor.Animation.CrossFade(animName);
        return null;
    }

    static ASTNode _set_active(List<ASTNode> args, Context context)
    {
        args = CoreFunction.EvalArgs(args, context);
        Actor curActor = (Actor)((ObjectNode)args[0]).Val;
        bool b = (bool)((BoolNode)args[1]).Val;
        curActor.gameObject.SetActive(b);
        return null;
    }
}
